package com.blueseaapps;

import java.util.UUID;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.blueseaapps.c2dm.C2DMBaseReceiver;
import com.blueseaapps.utility.RegistrationTokenManager;
import com.blueseaapps.utility.UserDataManager;

public class C2DMReceiver extends C2DMBaseReceiver {
	private static final String TAG = "C2DMReceiver";
	private static final int NEW_QUIZ_DOWNLOADED = 1;
    public C2DMReceiver() {
        super("blueseaapps@gmail.com");
    }

    @Override
    public void onRegistered(Context cxt, String regId) {
    	Log.d(TAG,"Received new Reg ID");
    	
    	String storedRegId = UserDataManager.getRegistrationId(cxt);
		if((storedRegId == null) || (! regId.trim().equals(storedRegId.trim()))){
			UserDataManager.setRegistrationId(cxt, regId);
			UUID uid = UserDataManager.getUniqueId(cxt);
			boolean status = RegistrationTokenManager.storeToken(regId,uid.toString());
			if(status){
				Log.d(TAG, "Registration Complete");
			}else{
				Log.d(TAG, "Registration Fail.");
			}
		}
//    	Intent startActivityIntent = new Intent(context,StartActivity.class);
//    	startActivityIntent.putExtra("com.blueseaapps.photoquiz.UPDATE_AVAILABLE", registration);
//    	startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//    	startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	
//    	context.startActivity(startActivityIntent);
    }

    private void postNotification(Context context) {
		// TODO Auto-generated method stub
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		
		Notification notification = new Notification(R.drawable.icon,"",System.currentTimeMillis());
		notification.flags = notification.flags|Notification.FLAG_AUTO_CANCEL;
		
    	Intent startActivityIntent = new Intent(context,StartActivity.class);
    	startActivityIntent.putExtra("com.blueseaapps.photoquiz.UPDATE_AVAILABLE", "New quiz available");
    	startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, startActivityIntent, 0);
		notification.setLatestEventInfo(context, "Photoquiz", "New Questions downloaded.", contentIntent);
		
		nm.notify(NEW_QUIZ_DOWNLOADED, notification);
	}

	@Override
    public void onUnregistered(Context context) {
//        SharedPreferences prefs = Prefs.get(context);
//        String deviceRegistrationID = prefs.getString("deviceRegistrationID", null);
//        DeviceRegistrar.unregisterWithServer(context, deviceRegistrationID);
    }

    @Override
    public void onError(Context context, String errorId) {
//        context.sendBroadcast(new Intent("com.google.ctp.UPDATE_UI"));
    }

    @Override
    public void onMessage(Context context, Intent intent) {
    	Log.d(TAG, "New quiz downloaded.");
    	postNotification(context);
//        Bundle extras = intent.getExtras();
//        if (extras != null) {
//            String url = (String) extras.get("url");
//            String title = (String) extras.get("title");
//            String sel = (String) extras.get("sel");
//            String debug = (String) extras.get("debug");
//
//            if (debug != null) {
//                // server-controlled debug - the server wants to know
//                // we received the message, and when. This is not user-controllable,
//                // we don't want extra traffic on the server or phone. Server may
//                // turn this on for a small percentage of requests or for users
//                // who report issues.
//                DefaultHttpClient client = new DefaultHttpClient();
//                HttpGet get = new HttpGet(AppEngineClient.BASE_URL + "/debug?id="
//                        + extras.get("collapse_key"));
//                // No auth - the purpose is only to generate a log/confirm delivery
//                // (to avoid overhead of getting the token)
//                try {
//                    client.execute(get);
//                } catch (ClientProtocolException e) {
//                    // ignore
//                } catch (IOException e) {
//                    // ignore
//                }
//            }
//
//            if (title != null && url != null && url.startsWith("http")) {
//                SharedPreferences settings = Prefs.get(context);
//                Intent launchIntent = LauncherUtils.getLaunchIntent(context, title, url, sel);
//
//                // Notify and optionally start activity
//                if (settings.getBoolean("launchBrowserOrMaps", true) && launchIntent != null) {
//                    try {
//                        context.startActivity(launchIntent);
//                        LauncherUtils.playNotificationSound(context);
//                    } catch (ActivityNotFoundException e) {
//                        return;
//                    }
//                } else {
//                    if (sel != null && sel.length() > 0) {  // have selection
//                        LauncherUtils.generateNotification(context, sel,
//                                context.getString(R.string.copied_desktop_clipboard), launchIntent);
//                    } else {
//                        LauncherUtils.generateNotification(context, url, title, launchIntent);
//                    }
//                }
//
//                // Record history (for link/maps only)
//                if (launchIntent != null && launchIntent.getAction().equals(Intent.ACTION_VIEW)) {
//                    HistoryDatabase.get(context).insertHistory(title, url);
//                }
//            }
//        }
    }
}

